package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 添加订单数据和订单明细
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {



        //生成订单号
        String orderNumber = UUID.randomUUID().toString();
        //拷贝属性
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //设置地址簿信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        BeanUtils.copyProperties(addressBook,orders);
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //设置订单号
        orders.setNumber(orderNumber);
        //设置用户id
        orders.setUserId(BaseContext.getCurrentId());
        //设置订单时间
        LocalDateTime now = LocalDateTime.now();
        orders.setOrderTime(now);
        //设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置支付状态
        orders.setPayStatus(Orders.UN_PAID);




        //插入一条订单数据
        orderMapper.submit(orders);

        List<ShoppingCart> shoppingCarts = shoppingCartMapper.find(orders.getUserId());

        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //插入订单明细数据
        orderDetailMapper.add(orderDetails);

        //清空购物车
        shoppingCartMapper.clean(orders.getUserId());

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO(orders.getId(),orderNumber,orders.getAmount(),now);
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

        //跳过微信平台，直接修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());

        //返回空对象（已经修改了前端）
        OrderPaymentVO vo = new OrderPaymentVO();


        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        //订单类型,1表示来单提醒,2表示催单
        map.put("type",1);
        //订单id
        map.put("orderId",ordersDB.getId());
        //消息具体内容
        map.put("content","订单号"+outTradeNo);

        String json = JSONObject.toJSONString(map);

        webSocketServer.sendToAllClient(json);

        orderMapper.update(orders);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO findByOrderId(Long id) {

        //查询订单数据
        Orders orders = orderMapper.findByOrderId(id);

        //查询订单明细数据
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(id);

        //构建VO对象
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(orderDetails);
        BeanUtils.copyProperties(orders,orderVO);
        return orderVO;
    }

    @Override
    public PageResult pageFind(Integer page, Integer pageSize, Integer status) {

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //1. 设置分页参数
        PageHelper.startPage(page,pageSize);

        //2.  执行查询
        Page<Orders> p = orderMapper.pageFind(ordersPageQueryDTO);

        List<OrderVO> orderVOs = new ArrayList<>();
        if(p.getTotal() > 0 && p != null){
            for (Orders orders : p) {
                List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(orders.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                orderVOs.add(orderVO);
            }
        }

        //3.  封装PageResult对象，包含查询的总记录数和查询结果
        PageResult pageResult=new PageResult(p.getTotal(),orderVOs);

        return pageResult;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {

        orderMapper.cancel(id);
    }

    /**
     * 再来一单(将原订单中的商品重新加入到购物车中)
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderdetails = orderDetailMapper.findByOrderId(id);

        for (OrderDetail orderdetail : orderdetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderdetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.add(shoppingCart);
        }
    }

    /**
     * 管理端分页查询订单
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pagequery(OrdersPageQueryDTO pageQueryDTO) {
        //1.指定分页参数
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());

        //2.执行查询
        Page<Orders> p = orderMapper.pageQuery(pageQueryDTO);

        //3.封装pageResult对象
        PageResult pageResult = new PageResult(p.getTotal(),p.getResult());

        return pageResult;
    }

    /**
     * 各订单状态数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistic() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();

        statisticsVO.setConfirmed(orderMapper.statistic(Orders.CONFIRMED));
        statisticsVO.setDeliveryInProgress(orderMapper.statistic(Orders.DELIVERY_IN_PROGRESS));
        statisticsVO.setToBeConfirmed(orderMapper.statistic(Orders.TO_BE_CONFIRMED));

        return statisticsVO;
    }

    /**
     * 接单
     */
    @Override
    public void confirm(OrdersDTO ordersDTO) {
        ordersDTO.setStatus(Orders.CONFIRMED);
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersDTO,orders);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param orders
     */
    @Override
    public void reject(Orders orders) {
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }


}
